<template>
  <view class="my-bottles-page">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="back-button" @click="handleBack">‹</text>
      <text class="header-title">我的瓶子</text>
    </view>

    <!-- 分段控件 -->
    <view class="segmented-control">
      <view 
        class="segment" 
        :class="{ active: currentTab === 'sent' }"
        @click="switchTab('sent')"
      >
        我投递的
      </view>
      <view 
        class="segment" 
        :class="{ active: currentTab === 'received' }"
        @click="switchTab('received')"
      >
        我收到的
      </view>
      <view 
        class="segment" 
        :class="{ active: currentTab === 'collected' }"
        @click="switchTab('collected')"
      >
        我的收藏
      </view>
    </view>

    <!-- 瓶子列表容器 -->
    <view class="bottle-list-container">
      <!-- 我投递的瓶子 -->
      <view 
        class="bottle-list" 
        :class="{ active: currentTab === 'sent' }"
        v-if="currentTab === 'sent'"
      >
        <view 
          class="bottle-item" 
          v-for="bottle in sentBottles" 
          :key="bottle.id"
          @click="handleBottleClick(bottle, 'sent')"
        >
          <text class="bottle-icon">➡️</text>
          <view class="bottle-info">
            <text class="bottle-content">{{ getBottlePreview(bottle.content) }}</text>
            <text class="bottle-meta">{{ getBottleMetaInfo(bottle) }}</text>
          </view>
          <view class="bottle-status" :class="getStatusClass(bottle.status)">
            {{ getStatusText(bottle.status) }}
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="sentBottles.length === 0">
          <text class="empty-text">暂无投递的瓶子</text>
        </view>
      </view>

      <!-- 我收到的瓶子 -->
      <view 
        class="bottle-list" 
        :class="{ active: currentTab === 'received' }"
        v-if="currentTab === 'received'"
      >
        <view 
          class="bottle-item" 
          v-for="bottle in receivedBottles" 
          :key="bottle.id"
          @click="handleBottleClick(bottle, 'received')"
        >
          <text class="bottle-icon">⬅️</text>
          <view class="bottle-info">
            <text class="bottle-content">{{ getBottlePreview(bottle.content) }}</text>
            <text class="bottle-meta">{{ getReceivedMetaInfo(bottle) }}</text>
          </view>
          <view class="bottle-status status-opened">
            已开启
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="receivedBottles.length === 0">
          <text class="empty-text">暂无收到的瓶子</text>
        </view>
      </view>

      <!-- 我的收藏 -->
      <view 
        class="bottle-list" 
        :class="{ active: currentTab === 'collected' }"
        v-if="currentTab === 'collected'"
      >
        <view 
          class="bottle-item" 
          v-for="bottle in collectedBottles" 
          :key="bottle.id"
          @click="handleBottleClick(bottle, 'collected')"
        >
          <text class="bottle-icon">⭐️</text>
          <view class="bottle-info">
            <text class="bottle-content">{{ getBottlePreview(bottle.content) }}</text>
            <text class="bottle-meta">{{ getCollectedMetaInfo(bottle) }}</text>
          </view>
          <view class="bottle-status status-collected">
            已收藏
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="collectedBottles.length === 0">
          <text class="empty-text">暂无收藏的瓶子</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useBottleStore } from '@/store/bottle'
import { useUserStore } from '@/store/user'
import dayjs from 'dayjs'

export default {
  name: 'MyBottlesPage',
  data() {
    return {
      currentTab: 'sent'
    }
  },
  
  computed: {
    bottleStore() {
      return useBottleStore()
    },
    
    userStore() {
      return useUserStore()
    },
    
    /**
     * 我投递的瓶子
     */
    sentBottles() {
      return this.bottleStore.sentBottles || []
    },
    
    /**
     * 我收到的瓶子
     */
    receivedBottles() {
      return this.bottleStore.receivedBottles || []
    },
    
    /**
     * 我的收藏
     */
    collectedBottles() {
      return this.bottleStore.collectedBottles || []
    }
  },
  
  onLoad() {
    console.log('我的瓶子页面加载')
    this.initPage()
  },
  
  onShow() {
    console.log('我的瓶子页面显示')
    // 刷新数据
    this.refreshData()
  },
  
  methods: {
    /**
     * 初始化页面
     */
    initPage() {
      // 加载瓶子数据
      this.bottleStore.loadFromStorage()
    },
    
    /**
     * 刷新数据
     */
    refreshData() {
      // 重新加载瓶子数据
      this.bottleStore.loadFromStorage()
    },
    
    /**
     * 处理返回
     */
    handleBack() {
      uni.navigateBack()
    },
    
    /**
     * 切换标签页
     */
    switchTab(tab) {
      this.currentTab = tab
    },
    
    /**
     * 处理瓶子点击
     */
    handleBottleClick(bottle, type) {
      console.log('点击瓶子:', bottle, type)
      
      // 根据类型处理不同的逻辑
      if (type === 'sent') {
        // 投递的瓶子，可以查看详情或撤回
        this.showBottleActions(bottle, type)
      } else if (type === 'received' || type === 'collected') {
        // 收到的瓶子或收藏的瓶子，可以查看详情
        this.showBottleDetail(bottle)
      }
    },
    
    /**
     * 显示瓶子操作
     */
    showBottleActions(bottle, type) {
      const actions = ['查看详情']
      
      // 根据状态添加不同的操作
      if (bottle.status === 'floating' || bottle.status === 'pending') {
        actions.push('撤回瓶子')
      }
      
      actions.push('删除瓶子')
      actions.push('取消')
      
      uni.showActionSheet({
        itemList: actions,
        success: (res) => {
          const action = actions[res.tapIndex]
          
          if (action === '查看详情') {
            this.showBottleDetail(bottle)
          } else if (action === '撤回瓶子') {
            this.recallBottle(bottle)
          } else if (action === '删除瓶子') {
            this.deleteBottle(bottle, type)
          }
        }
      })
    },
    
    /**
     * 显示瓶子详情
     */
    showBottleDetail(bottle) {
      uni.showModal({
        title: '瓶子详情',
        content: bottle.content,
        showCancel: false,
        confirmText: '确定'
      })
    },
    
    /**
     * 撤回瓶子
     */
    async recallBottle(bottle) {
      uni.showModal({
        title: '确认撤回',
        content: '确定要撤回这个瓶子吗？撤回后瓶子将不再流转。',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await this.bottleStore.recallBottle(bottle.id)
              
              if (result.success) {
                uni.showToast({
                  title: '撤回成功',
                  icon: 'success'
                })
                
                // 刷新数据
                this.refreshData()
              } else {
                uni.showToast({
                  title: result.message || '撤回失败',
                  icon: 'error'
                })
              }
            } catch (error) {
              console.error('撤回瓶子失败:', error)
              uni.showToast({
                title: '撤回失败',
                icon: 'error'
              })
            }
          }
        }
      })
    },
    
    /**
     * 删除瓶子
     */
    async deleteBottle(bottle, type) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个瓶子吗？删除后无法恢复。',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await this.bottleStore.deleteBottle(bottle.id, type)
              
              if (result.success) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                
                // 刷新数据
                this.refreshData()
              } else {
                uni.showToast({
                  title: result.message || '删除失败',
                  icon: 'error'
                })
              }
            } catch (error) {
              console.error('删除瓶子失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'error'
              })
            }
          }
        }
      })
    },
    
    /**
     * 获取瓶子内容预览
     */
    getBottlePreview(content) {
      if (!content) return '暂无内容'
      return content.length > 20 ? content.substring(0, 20) + '...' : content
    },
    
    /**
     * 获取瓶子元信息
     */
    getBottleMetaInfo(bottle) {
      if (!bottle) return ''
      
      const typeText = bottle.type === 'private' ? '时光瓶' : '公开瓶'
      const dateText = dayjs(bottle.createdAt).format('YYYY-MM-DD')
      
      return `${typeText} · ${dateText}`
    },
    
    /**
     * 获取收到瓶子元信息
     */
    getReceivedMetaInfo(bottle) {
      if (!bottle || !bottle.sender) return ''
      
      const senderName = bottle.isAnonymous ? '匿名用户' : bottle.sender.nickname
      const dateText = dayjs(bottle.receivedAt || bottle.createdAt).format('YYYY-MM-DD')
      
      return `来自 ${senderName} · ${dateText}`
    },
    
    /**
     * 获取收藏瓶子元信息
     */
    getCollectedMetaInfo(bottle) {
      if (!bottle || !bottle.sender) return ''
      
      const senderName = bottle.isAnonymous ? '匿名用户' : bottle.sender.nickname
      const dateText = dayjs(bottle.collectedAt || bottle.createdAt).format('YYYY-MM-DD')
      
      return `来自 ${senderName} · ${dateText}`
    },
    
    /**
     * 获取状态样式类
     */
    getStatusClass(status) {
      switch (status) {
        case 'floating':
          return 'status-floating'
        case 'opened':
          return 'status-opened'
        case 'lost':
          return 'status-lost'
        case 'collected':
          return 'status-collected'
        case 'pending':
          return 'status-pending'
        default:
          return 'status-default'
      }
    },
    
    /**
     * 获取状态文本
     */
    getStatusText(status) {
      switch (status) {
        case 'floating':
          return '漂流中'
        case 'opened':
          return '已开启'
        case 'lost':
          return '已迷失'
        case 'collected':
          return '已收藏'
        case 'pending':
          return '待开启'
        case 'recalled':
          return '已撤回'
        default:
          return '未知状态'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.my-bottles-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--primary-bg);
  color: var(--text-light);
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.page-header {
  display: flex;
  align-items: center;
  padding: 40rpx;
  padding-top: 100rpx; /* 适配状态栏 */
  flex-shrink: 0;
  border-bottom: 1rpx solid var(--lighter-bg);
  
  .back-button {
    font-size: 48rpx;
    color: var(--text-light);
    margin-right: 40rpx;
    font-weight: 300;
  }
  
  .header-title {
    font-size: 36rpx;
    font-weight: 500;
    color: var(--text-light);
  }
}

.segmented-control {
  display: flex;
  justify-content: center;
  padding: 30rpx;
  flex-shrink: 0;
  
  .segment {
    padding: 16rpx 40rpx;
    color: var(--text-dark);
    border-bottom: 4rpx solid transparent;
    transition: all 0.3s ease;
    font-size: 28rpx;
    
    &.active {
      color: var(--accent-gold);
      border-bottom-color: var(--accent-gold);
    }
  }
}

.bottle-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 40rpx;
  
  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 8rpx;
  }
  
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  
  &::-webkit-scrollbar-thumb {
    background: var(--text-dark);
    border-radius: 8rpx;
  }
}

.bottle-list {
  display: block;
  
  .bottle-item {
    display: flex;
    align-items: center;
    background-color: rgba(65, 90, 119, 0.5);
    padding: 30rpx;
    border-radius: 24rpx;
    margin-bottom: 30rpx;
    
    .bottle-icon {
      font-size: 48rpx;
      margin-right: 30rpx;
    }
    
    .bottle-info {
      flex: 1;
      
      .bottle-content {
        display: block;
        font-size: 32rpx;
        color: var(--text-light);
        margin-bottom: 16rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .bottle-meta {
        font-size: 24rpx;
        color: var(--text-dark);
      }
    }
    
    .bottle-status {
      padding: 8rpx 16rpx;
      border-radius: 12rpx;
      font-size: 24rpx;
      font-weight: 500;
      
      &.status-floating {
        background-color: var(--status-blue);
        color: white;
      }
      
      &.status-opened {
        background-color: var(--status-green);
        color: white;
      }
      
      &.status-lost {
        background-color: var(--status-grey);
        color: white;
      }
      
      &.status-collected {
        background-color: var(--accent-gold);
        color: var(--primary-bg);
      }
      
      &.status-pending {
        background-color: var(--lighter-bg);
        color: var(--text-light);
      }
    }
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  
  .empty-text {
    font-size: 32rpx;
    color: var(--text-dark);
  }
}
</style> 